﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Data.SugarClient.Soap.V1
{
	internal class V1GetModuleFieldsAction : V1ModuleAction
	{

		private static IDictionary<int, V1GetModuleFieldsActionResult> _cache = new Dictionary<int, V1GetModuleFieldsActionResult>(10);

		#region Constructors

		internal V1GetModuleFieldsAction(
			SugarSoapV1.sugarsoap service,
			string session,
			string moduleName)
			: base(service, session, moduleName) 
		{
		}

		#endregion

		#region Methods

		protected override V1ActionResult ExecuteInner()
		{
			return FindFromCache() ?? ExecuteSoap();
		}

		protected V1GetModuleFieldsActionResult FindFromCache()
		{
			Trace.Debug("{0}.FindFromCache(),Session:{1},Module:{2}", this.GetType().Name, this.Session, this.Module);
			int hash = (this.Session.GetHashCode() + this.Module.GetHashCode()).GetHashCode();
			return (_cache.ContainsKey(hash)) ? _cache[hash] : null;
		}

		protected V1GetModuleFieldsActionResult ExecuteSoap()
		{
			Trace.Debug("{0}.ExecuteSoap(),Session:{1}", this.GetType().Name, this.Session, this.Module);
			var soap =
				this.SoapService.get_module_fields(
					this.Session,
					this.Module);
			V1GetModuleFieldsActionResult result = new V1GetModuleFieldsActionResult(this, soap);
			if (10 <= _cache.Count) _cache.Clear();
			_cache[(this.Session.GetHashCode() + this.Module.GetHashCode()).GetHashCode()] = result;
			return result;
		}

		#endregion
	}

	internal class V1GetModuleFieldsActionResult : V1ModuleActionResult, IGetModuleFieldsActionResult
	{

		internal V1GetModuleFieldsActionResult(
			V1GetModuleFieldsAction action,
			SugarSoapV1.module_fields result)
			: base(action)
		{
			this._soapResult = result;
			this._varDefs = ToSugarVarDef(result.module_fields1);
		}

		#region Fields

		private readonly SugarSoapV1.module_fields _soapResult;
		private readonly IList<SugarVarDef> _varDefs;

		#endregion

		#region Properties

		internal SugarSoapV1.module_fields SoapResult
		{
			get { return _soapResult; }
		}

		public IList<SugarVarDef> VarDefs
		{
			get { return _varDefs; }
		}

		internal virtual bool Success
		{
			get
			{
				if (SoapResult.error == null) return true;
				else if (SoapResult.error.number == null) return true;
				else if ("0".Equals(SoapResult.error.number)) return true;
				else return false;
			}
		}

		#endregion

		internal static IList<SugarVarDef> ToSugarVarDef(SugarSoapV1.field[] source)
		{
			List<SugarVarDef> vardefs = new List<SugarVarDef>();
			foreach (SugarSoapV1.field field in source)
			{
				vardefs.Add(SugarVarDef.Create(field));
			}
			return vardefs;
		}
	}

}
